<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" :model="listQuery" @submit.native.prevent label-width="110px">
        <el-form-item label="机构名称:" class="form-item">
          <el-input v-model="listQuery.orgName" class="filter-item" placeholder="机构名称"/>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="table_content">
      <div class="btn-btm">
        <el-button type="primary" size="mini" plain icon="el-icon-plus" @click="handleAdd">添加
        </el-button>
      </div>
      <!--表格渲染-->
      <el-table ref="table" v-loading="loading" :data="list" style="width: 100%;" border
                :header-cell-style="{background: '#F8F8F9',padding: '6px 0 !important',color: '#515a6e'}"
                row-key="orgID" default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="orgName" fixed="left" label="部门名称" />
        <!--<af-table-column prop="level" label="级别" />-->
        <el-table-column prop="remark" label="说明" />
        <el-table-column prop="timeAdd" label="增加时间" />
        <el-table-column fixed="right" label="操作" min-width="100">
          <template slot-scope="scope">
            <el-button class="btn" type="text" size="small" v-if="scope.row.orgLevel != 0"
                       @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
            <el-popover
              placement="top"
              width="200"
              trigger="manual"
              :ref="'popover-' + scope.row.orgID">
              <p>确定删除该数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.orgID].doClose()">取消</el-button>
                <el-button type="primary" size="mini" @click="handleDel(scope.$index,scope.row)">确定</el-button>
              </div>
              <el-button class="btn" type="text" size="small" slot="reference"
                         v-if="scope.row.orgLevel != 0"
                         @click="$refs[`popover-` + scope.row.orgID].doShow()">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--表单添加-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="30%">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
        <!--<el-form-item label="级别:" prop="orgLevel" class="form-item" v-if="dialogStatus == 'create'">
          <el-select placeholder="请选择" style="width:100%;" clearable v-model="editForm.orgLevel"
                     class="form-select" :popper-append-to-body="false" popper-class="select-popper">
            <el-option :value="0" label="一级"></el-option>
            <el-option :value="1" label="二级"></el-option>
            <el-option :value="2" label="三级"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="上级部门:" prop="upOrgName" class="form-item">
          <el-select v-model="editForm.upOrgName" placeholder="请选择" ref="selectReport"
                     popper-class="select-popper" class="form-select"
                     :popper-append-to-body="false">
            <el-option
              :value="editForm.orgID"
              :label="editForm.orgName"
              style="
                width: 450px;
                height: 200px;
                overflow: auto;
                background-color: #fff;
              "
            >
              <el-tree
                :data="list"
                :props="{value: 'orgID',label: 'orgName',}"
                @node-click="handleNodeClick"
              ></el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构名称:" prop="orgName" class="form-item">
          <el-input v-model="editForm.orgName" class="filter-item" placeholder="机构名称"/>
        </el-form-item>
        <el-form-item label="说明:" prop="remark" class="form-item">
          <el-input v-model="editForm.remark" type="textarea" autosize
                    :autosize="{ minRows: 2, maxRows: 4}" class="filter-item" placeholder="说明"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" size="mini" @click="createData">
          {{dialogStatus == 'create'?'添加':'保存'}}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { doPost, doGet, doFile, orglistChild } from '@/api/index'
  import { mapGetters } from 'vuex'
  import Pagination from '@/components/Pagination/index'

  export default {
    name: "org",
    components: { Pagination },
    data() {
      return{
        loading: false,
        list: [],
        listQuery: {
          orgName: ''
        },
        dialogStatus: '',
        textMap:{
          update: '编辑',
          create: '新增'
        },
        dialogFormVisible: false,
        editForm: {
          orgName: '',
          remark: '',
          orgLevel: '',
          upOrgID: '',
          upOrgName: ''
        },
        editFormRules: {
          orgLevel: [{ required: true, message: '级别不能为空', trigger: 'blur' }],
          upOrgName: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
          orgName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
        },
        deptOptions: []
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.loading = true
        orglistChild(this.listQuery).then(res=> {
          this.loading = false
          this.list = res.data
        }).catch(error => {
          this.loading = false
          this.list = []
        })
      },
      //添加
      handleAdd() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.editForm = {
          orgName: '',
          remark: '',
          orgLevel: '',
          upOrgID: '',
          upOrgName: ''
        }
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      //编辑弹窗
      handleEdit(index, row) {
        if (row) {
          for (var key in row) {
            if (row[key] == null || typeof(row[key]) === "undefined" || row[key] == undefined) {
              row[key] = ''
            }
          }
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.editForm = Object.assign({}, row)
        this.getOptionsNames(row.upOrgID)
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      getTreeName(list,id){
        for (let i = 0; i < list.length; i++) {
          if(list[i].orgID===id){
            return list[i].orgName
          }else if(list[i].children && list[i].children.length>0){
            let res = this.getTreeName(list[i].children,id)
            if(res){
              return res
            }
          }
        }
      },
      getOptionsNames(id){
        let newArr;
        newArr = this.getTreeName(this.list,id)
        this.editForm.upOrgName = newArr
        console.log('newArr',newArr);
      },
      //提交表单
      createData() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            if (this.editForm.upOrgID == null || typeof(this.editForm.upOrgID) === "undefined" || this.editForm.upOrgID == undefined) {
              this.editForm.upOrgID = ''
            }
            doPost(`organize/${this.dialogStatus == 'create' ? 'add' : 'update'}`,this.editForm).then(res => {
              if (res.code == 200){
                this.dialogFormVisible = false
                this.getList()
                this.$message.success({
                  message: this.dialogStatus == 'create'?'提交成功':'保存成功',
                  type: 'success'
                })
              } else {
                this.$message.error(res.message)
              }
            }).catch(error => {
              this.$message.error(error.message)
            })
          }
        })
      },
      //删除列表
      handleDel(index,row) {
        doPost('organize/delete/'+row.orgID)
          .then(res => {
            this.$message.success({
              type: 'success',
              message: '删除成功'
            })
            this.getList()
            // this.list.splice(index, 1)
            // this.total--
            this.$refs[`popover-` + row.orgID].doClose()
          }).catch(error => {
          this.$refs[`popover-` + row.orgID].doClose()
          this.$message.error(error.message)
        })
      },
      // 上级选择
      handleNodeClick(val) {
        this.editForm.orgLevel += val.orgLevel + 1
        this.$set(this.editForm, "upOrgID", val.orgID);
        this.$set(this.editForm, "upOrgName", val.orgName);
        if (!val.children || val.children.length == 0) {
          this.$refs.selectReport.blur();
        }
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
